<?php
namespace zzcms\primary\controller;

use think\Controller;
use think\Request;

class Base extends Controller
{
    protected $request;
    protected $info;
    protected $userid;
    private $tmp = '';
    protected $base_image_url = 'http://res.xuexiba.net/';


    protected function initialize()
    {
        header("Content-Type:text/html; charset=utf-8");
        header("Access-Control-Allow-Origin: *"); # 跨域处理
        header('Access-Control-Allow-Methods:POST');
        header('Access-Control-Allow-Headers:x-requested-with,content-type');
        if (!$this->request->isPost()) {
            $this->array2json(['code' => 1, 'msg' => '非法请求']);
        }
        $this->info = $this->request->post();
        $this->checkAccessToken($this->info);
    }

    //把数组转成json字符串
    protected function array2json($array)
    {
        exit(json_encode($array, JSON_UNESCAPED_UNICODE));
    }


    /**
     * 新版签名
     * 签名规则:根据传递过来的数组组装成一维数组，去掉sign, timestamp，去掉空值，进行字典序排列，然后进行http_build_query组装成字符串,然后连接上$key，$time依次进行base64_encode,md5和strtoupper处理
     */
    private function checkAccessToken($post)
    {
        if (!isset($post['timestamp']) || !isset($post['sign'])) {
            $this->array2json(['code' => 1, 'msg' => '缺少参数']);
        }
        if (time() - $post['timestamp'] > 30) {
            $this->array2json(['code' => 1, 'msg' => '请求已过期']);
        }
        $arr = $_POST;
        $sign = $arr['sign'];
        $key_code = '458f_$#@$*!fdjisdJDFHUk4%%653154%^@#(FSD#$@0-T';
        $data = $this->createTokenString($arr) . $key_code . $post['timestamp'];
        $mysign = strtoupper(md5(base64_encode($data)));
        if ($sign != $mysign) {
            $this->array2json(['code' => 1, 'msg' => '认证错误', 'data' => $mysign]);
        }
    }

    //根据传递过来的值组装成一维数组，去掉sign，去掉空值，进行字典序排列，然后进行http_build_query组装成字符串
    private function createTokenString($arr)
    {
        if (!is_array($arr)) {
            return false;
        }
        foreach ($arr as $key => $val) {
            if (is_array($val)) {
                $this->createTokenString($val);
            } else {
                if ($key == 'sign' || $key == 'timestamp' || strlen($val) < 1) {
                    continue;
                } else {
                    $this->tmp .= $val . ',';
                }
            }
        }
        return substr($this->tmp, 0, -1);
    }
}